package com.aaa.security;

import com.aaa.entity.ResponseMsg;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 未认证处理器：用户没有登录，访问资源
 */
@Component
public class EntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        // 响应设置
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Type","application/json");
        httpServletResponse.setStatus(200);
        ResponseMsg responseMsg = new ResponseMsg(503, "未认证", e.getMessage());

        // FastJSON
        // 写：字符输出流
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONObject.toJSONString(responseMsg));
        writer.flush();
        writer.close();
    }
}
